let listeners = [];

class WindowEventPublisher {
  addListener(eventName, callback) {
    let alreadyExists = false;

    // 遍历所有的 listeners 并查找是否存在相同的监听器
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i];
      if (listener.eventName === eventName && listener.callback.toString() === callback.toString()) {
        alreadyExists = true;
        break;
      }
    }

    // 如果不存在相同的监听则进行添加
    if (!alreadyExists) {
      window.addEventListener(eventName, callback);
      listeners.push({ eventName, callback });
    }
  }

  removeListener(eventName, callback) {
    // 移除指定的事件监听器
    window.removeEventListener(eventName, callback);

    // 从 listeners 数组中移除对应项
    listeners = listeners.filter(
      (l) => l.eventName !== eventName || l.callback.toString() !== callback.toString()
    );
  }
}

export default new WindowEventPublisher();
